'''
Created on Jan 10, 2010

@author: user
'''
import os
import cliques.utils
import logging
import graph

class folderIndexGraphGenerator(object):
    def __init__(self,folder_name):
        self.folder_name = folder_name
        self.graphs = []
        self.graph_names = []
        for file_name in os.listdir(self.folder_name):
            if file_name.endswith("index-graph.dot"):
                logging.info("Loading %s..." % file_name)
                a_graph = cliques.utils.import_graph(self.folder_name + "/" + file_name,'dot')
                a_graph = self.isomorph_graph_to_sequential_indices(a_graph)
                self.graphs.append(a_graph)
                self.graph_names.append(file_name)
        self.index = len(self.graphs)

    def isomorph_graph_to_sequential_indices(self,a_graph):
        ''' Make every node index equal to a node '''
        nodes = a_graph.nodes()
        node_to_index = dict()
        ordered_graph = graph.graph()
        for index in xrange(len(nodes)):
            ordered_graph.add_node(index)
            node_to_index[nodes[index]]=index
        for node in nodes:
            for neighbor in a_graph.neighbors(node):
                ordered_graph.add_edge(node_to_index[node],node_to_index[neighbor])        
        return ordered_graph

    def createIndexGraphFromFolder(self,indexA,indexB):       
        self.index = self.index-1
        logging.info("Creating graph from file %s" % self.graph_names[self.index])
        return self.graphs[self.index]
